package com.frost.musicplayer.controller;

import com.frost.musicplayer.mapper.LoveMusicMapper;
import com.frost.musicplayer.mapper.MusicMapper;
import com.frost.musicplayer.model.Music;
import com.frost.musicplayer.model.User;
import com.frost.musicplayer.tools.Constant;
import com.frost.musicplayer.tools.ResponseBodyMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {

    @Value("${music.local.path}")
    private String SAVE_PATH/* = "D:/tmp/music/"*/;

    @Autowired
    private MusicMapper musicMapper;

    @Resource
    private LoveMusicMapper loveMusicMapper;

    // 1. 服务器上传 2. 数据库上传
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer,
                                                    @RequestParam("filename") MultipartFile file,
                                                    HttpServletRequest request,
                                                    HttpServletResponse resp) throws IOException {
        // 1. 检查是否登录
        HttpSession httpSession = request.getSession(false);
        if (httpSession == null || httpSession.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            System.out.println("没有登录!");
            return new ResponseBodyMessage<>(-1, "请登录后上传", false);
        }

        // 查询数据库, 判断是否有当前歌曲
        // TODO:


        // 服务器上传
        String fileNameAndType = file.getOriginalFilename();
        System.out.println("fileNameAndType: " + fileNameAndType);

        String path = SAVE_PATH + "/" + fileNameAndType;
        System.out.println(path);

        File dest = new File(path);
        System.out.println(dest);

        if (!dest.exists()) {
            dest.mkdir();
        }

        try {
            file.transferTo(dest);
//            return new ResponseBodyMessage<>(0, "上传成功", true);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseBodyMessage<>(-1, "服务器上传失败", false);
        }

        // 进行数据库的上传
        // 1. 准备数据   2. 调用insert
        int index = fileNameAndType.lastIndexOf(".");
        String title = fileNameAndType.substring(0, index);

        User user = (User) httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userid = user.getId();

        // 播放音乐 --》 http 请求
        String url =  "/music/get?path=" + title;

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sf.format(new Date());

        try {
            int ret = 0;
            ret = musicMapper.insert(title, singer, time, url, userid);

            if (ret == 1) {
                // 跳转音乐列表页面
                resp.sendRedirect("/list.html");
                return new ResponseBodyMessage<>(0, "数据库上传成功", true);
            } else {
                return new ResponseBodyMessage<>(-1, "数据库上传失败", false);
            }
        }catch (BindingException e) {
            dest.delete();
            return new ResponseBodyMessage<>(-1, "数据库上传失败", false);
        }
    }

    @RequestMapping("/get")
    public ResponseEntity<byte[]> func(String path){
        File file = new File(SAVE_PATH + "/" + path);
        byte[] a = new byte[0];
        try {
            a = Files.readAllBytes(file.toPath());
            if (a == null) {
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 删除单个音乐
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public ResponseBodyMessage<Boolean> deleteMusicById(@RequestParam String id) {
        // 1. 先检查这个音乐是否存在
        int iid = Integer.parseInt(id);
        // 2. 如果存在进行要删除
        Music music = musicMapper.findMusicById(iid);
        if (music == null) {
            System.out.println("没有这个id的音乐");
            return new ResponseBodyMessage<>(-1, "要删除的音乐不存在", false);
        }else {
            // 2.1 删除数据库
            int ret = musicMapper.deleteMusicById(iid);
            if (ret == 1) {
                // 2.2 删除服务器上的数据
//                int index = music.getUrl().lastIndexOf("=");
//                String fileName = music.getUrl().substring(index+1);
                String path = SAVE_PATH + "/" + music.getTitle() + ".mp3";
                File file = new File(path);

                if (file.delete()) {
                    // 同步删除 lovemusic 中的数据
                    loveMusicMapper.deleteLoveMusicByMusicId(iid);
                    return new ResponseBodyMessage<>(0, "删除成功", true);
                }else {
                    // 数据库删除成功但服务器未删除成，需要恢复数据库的信息

                    return new ResponseBodyMessage<>(-1, "服务器中的音乐删除失败", false);
                }

            }else {
                return new ResponseBodyMessage<>(-1, "数据库中的音乐删除失败", false);
            }
        }
    }

    /**
     * 批量进行删除
     * @param id
     * @return
     */
    @RequestMapping("/deleteSel")
    public ResponseBodyMessage<Boolean> deleteSelMusicById(@RequestParam("id[]") List<Integer> id) {
        System.out.println("id[]" + id);
        int sum = 0;
        for (int i = 0; i < id.size(); i++) {
            int musicId = id.get(i);
            Music music = musicMapper.findMusicById(musicId);
            if (music == null) {
                System.out.println("没有这个id的音乐");
                return new ResponseBodyMessage<>(-1, "要删除的音乐不存在", false);
            }
            // 删除数据库
            int ret = musicMapper.deleteMusicById(musicId);
            if (ret == 1) {
                // 删除服务器上的数据
                String path = SAVE_PATH + "/" + music.getTitle() + ".mp3";
                File file = new File(path);

                if (file.delete()) {
//                    return new ResponseBodyMessage<>(0, "删除成功", true);
                    // 同步删除 lovemusic 中的数据
                    loveMusicMapper.deleteLoveMusicByMusicId(musicId);
                    sum += ret;
                }else {
                    // 数据库删除成功但服务器未删除成，需要恢复数据库的信息

                    return new ResponseBodyMessage<>(-1, "服务器中的音乐删除失败", false);
                }
            }else {
                return new ResponseBodyMessage<>(-1, "数据库中的音乐删除失败", false);
            }
        }

        if (sum == id.size()) {
            return new ResponseBodyMessage<>(0, "批量删除成功", true);
        }else {
            return new ResponseBodyMessage<>(-1, "批量删除失败", false);
        }
    }

    @RequestMapping("/findmusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName) {
        List<Music> musicList = new ArrayList<>();
        log.info("musicName: " + musicName);
        if (musicName != null) {
            musicList = musicMapper.findMusicByName(musicName);
        }else {
            musicList = musicMapper.findMusic();
        }

        return new ResponseBodyMessage<>(0, "查询到了所有音乐", musicList);
    }

}
